package com.allenkerr.aspect;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * Created by 小柯(Allen Kerr) on 17.6.4 14:23.
 */
@Aspect
@Component
public class HttpAspect {

    private static final Logger LOGGER = LoggerFactory.getLogger(HttpAspect.class);

    @Pointcut("execution(public * com.allenkerr.controller.GirlController.*(..))")
    public void log() {
    }

    //@Before("execution(public * com.allenkerr.controller.GirlController.*(..))")
    @Before("log()")
    public void doBefore(JoinPoint joinPoint) {
        LOGGER.info("==> HttpAspect.doBefore");

        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();

        //url
        LOGGER.info("url = {}", request.getRequestURL());
        //method
        LOGGER.info("method = {}", request.getMethod());
        //ip
        LOGGER.info("ip = {}", request.getRemoteAddr());
        //类.方法
        LOGGER.info("class.method = {}", joinPoint.getSignature().getDeclaringTypeName() + "."
                + joinPoint.getSignature().getName());
        //参数
        LOGGER.info("args = {}", joinPoint.getArgs());
    }

    //@After("execution(public * com.allenkerr.controller.GirlController.*(..))")
    @After("log()")
    public void doAfter() {
        LOGGER.info("==> HttpAspect.doAfter");
    }

    @AfterReturning(pointcut = "log()", returning = "object")
    public void doAfterReturning(Object object) {
        LOGGER.info("==> HttpAspect.doAfterReturning");
        LOGGER.info("response = {}", object);
    }

}
